package com.finger.controller;

import com.finger.WordPracticeApplication;
import com.finger.controller.utils.R;
import com.finger.dao.UserDao;
import com.finger.dao.WordDao;
import com.finger.pojo.Source;
import com.finger.pojo.User;
import com.finger.pojo.Word;
import com.finger.pojo.dto.LearnedWordDto;
import com.finger.pojo.dto.SourceManageDto;
import com.finger.service.UserService;
import com.finger.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/words")
@CrossOrigin(origins = "*", allowedHeaders = {"Content-Type", "Authorization"})
public class WordController {
    @Autowired
    private WordService wordService;
    @Autowired
    private UserService userService;
    @Autowired
    private WordDao wordDao;
    @Autowired
    private UserDao userDao;
    private User userInfo;

    // 新增词汇
    @PostMapping()
    public R addWord(@RequestBody Word word) {
        return new R(true,wordDao.addWord(word),"添加单词成功");
    }

    // 修改词汇
    @PutMapping()
    public R updateWord(@RequestBody Word word) {
        wordDao.updateWordValue(word);
        wordDao.updateWordExplain(word);
        wordDao.updateWordSource(word);
        return new R(true,true,"修改单词成功");
    }
    // 删除词汇
    @DeleteMapping()
    public R deleteWord(@RequestParam("id") Integer id) {
        return new R(true,wordDao.deleteWord(id),"删除单词成功");
    }

    //给用户发送一条英语单词数据
    @GetMapping("/getWord/{id}")
    public R getWord(@PathVariable Integer id) {
        //通过用户id拿到用户信息
        User user = userService.getUserById(id);
        Word word = wordService.getWord(user);
        this.userInfo = user;
        if (word != null) {
            // 查看当前单词是否被收藏
            Integer collectionNum = wordDao.getWordCollectionStatus(id, word.getId());
            if (collectionNum != null) { // 当前单词被收藏了
                word.setCollection(collectionNum);
            }
            return new R(true, word, "get word ok!");
        } else {
            return new R(true, null, "get word error!");
        }
    }

    //用户提交一条单词信息
    @PostMapping("/sendWord/{id}")
    public R sendWord(@RequestBody Word word, @PathVariable int id) {
        Boolean flag = wordService.sendWord(word, id);
        if (flag) {
            //提交成功
            return new R(true, null, "提交成功");
        } else {
            //提交失败
            return new R(true, null, "提交失败");
        }
    }

    //返回提示语数据
    @GetMapping("/prompts")
    public R sendPrompt() {
        return new R(true, wordService.getPrompts(), "获取成功");
    }

    //获取用户已学习单词
    @GetMapping("/learned_words/{uid}")
    public R getLearnedWords(@PathVariable Integer uid) {
        List<LearnedWordDto> learnedWordDtos = wordDao.getUserLearnedWords10ByUid(uid);
        for (LearnedWordDto learnedWordDto : learnedWordDtos) {
            // 定义一个时间戳
            // long timestamp = 1620108022000L; // 2021-05-04 12:40:22

            // 创建一个Date对象，使用时间戳
            Date date = new Date(Long.parseLong(learnedWordDto.getLastSubmissionTime()));

            // 使用SimpleDateFormat类格式化日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(date);
            learnedWordDto.setLastSubmissionTime(formattedDate);
        }

        return new R(true, learnedWordDtos, "获取用户最近学习的10条数据成功");
    }

    ;

    // 切换当前单词收藏状态
    @PostMapping("/collection")
    public R switchCollection(@RequestParam("uid") Integer uid, @RequestParam("wid") Integer wid) {
        Integer collectionNum = wordDao.getWordCollectionStatus(uid, wid);
        if (collectionNum != null) {
            // 被收藏的情况
            wordDao.deleteCollectionById(collectionNum);
        }else {
            // 未被收藏的情况
            wordDao.createCollectionByUidAndWid(uid,wid);
        }

        return new R(true,"操作成功");
    }

    // 获取收藏夹单词
    @GetMapping("/collection/{uid}")
    public R getCollectionWords(@PathVariable("uid") Integer uid) {
        List<Word> collectionWords = wordDao.getCollectionWords(uid);
        if (collectionWords.isEmpty() || collectionWords == null) {
            return new R(false,"当前收藏夹中还未添加内容~");
        }
        return new R(true,collectionWords,"获取收藏夹单词信息成功");
    }

    // 获取词源管理info
    @GetMapping("/sourceManage/{uid}")
    public R getSourceManage(@PathVariable("uid") Integer uid) {
        SourceManageDto data = new SourceManageDto();
        User user = userDao.getUserById(uid);
        // 设置用户当前的词源id
        data.setNow_source(user.getSource());
        // 设置用户当前词源的name
        data.setNow_source_name(wordDao.getSourceById(user.getSource()).getName());
        // 设置当前用户的所有词源基本信息
        data.setSourceList(wordDao.getUserSourceInfo(uid));
        // 系统管理员获取所有词源信息
        if ("admin".equals(user.getUsername())) {
            data.setSourceList(wordDao.adminGetUserSourceInfo());
            for (Source source : data.getSourceList()) {
                if (source.getSource_id().equals(1)) {
                    // 为系统词源添加作者
                    source.setCreate_user_name("admin");
                    // 只有一个系统词源，找到后赋值作者，然后break退出循环
                    break;
                }
            }
        }
        // 设置当前用户当前词源的所有单词信息
        data.setNow_source_wordList(wordDao.getWordsBySource(data.getNow_source()));
        data.setNow_source_wordList_length(data.getNow_source_wordList().size());
        return new R(true,data,"获取词源管理信息成功");
    }

}
